package edu.sias.hyznxfapi.face.baidu.test;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;


/**
 * 需要添加依赖
 * <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
 * <dependency>
 *     <groupId>com.squareup.okhttp3</groupId>
 *     <artifactId>okhttp</artifactId>
 *     <version>4.12.0</version>
 * </dependency>
 */

/**
 *     public static String APP_ID = "118071722";
 *     public static String API_KEY = "YWcHE8SRAajHrNotReASEB33";
 *     public static String SECRET_KEY = "ZeYuIjxh4fbojMEF8lG6l5Uk6uOsx4G5";
 */
public class GetToken {
    public static final String API_KEY = "YWcHE8SRAajHrNotReASEB33";
    public static final String SECRET_KEY = "ZeYuIjxh4fbojMEF8lG6l5Uk6uOsx4G5";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

//    public static void main(String []args) throws IOException{
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, "{\"image_type\":\"BASE64\"}");
//        Request request = new Request.Builder()
//            .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + getAccessToken())
//            .method("POST", body)
//            .addHeader("Content-Type", "application/json")
//            .build();
//        Response response = HTTP_CLIENT.newCall(request).execute();
//        System.out.println(response.body().string());
//
//    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    public String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
